<template>
    <div>
        <el-dialog 
            title="用户信息" 
            :visible.sync="isShow" 
            @close="closeDialog"
            width="500px"
        >
            <el-form 
                :model="userForm" 
                :rules="rules" 
                ref="ruleForm" 
                label-width="100px"
            >
                <el-form-item label="员工" prop="empno">
                    <el-select 
                        v-model="userForm.empno" 
                        placeholder="请选择员工" 
                        :disabled="isEdit"
                        filterable
                    >
                        <el-option 
                            v-for="emp in newEmpList" 
                            :label="emp.empno + ' - ' + emp.ename"
                            :value="emp.empno" 
                            :key="emp.empno"
                        ></el-option>
                    </el-select>
                </el-form-item>
  
                <el-form-item label="账号">
                    <el-input 
                        v-model="userForm.empno" 
                        placeholder="请输入账号"
                        readonly=""
                        :disabled="isEdit"
                    ></el-input>
                </el-form-item>

                <el-form-item label="角色" prop="roleIds">
                    <el-select 
                        v-model="userForm.roleIds" 
                        multiple 
                        placeholder="请选择角色"
                        @change="handleRoleChange"
                        ref="roleSelect"
                    >
                        <el-option 
                            v-for="role in roleList" 
                            :label="role.rolename" 
                            :value="role.roleid"  
                            :key="role.roleid"
                        ></el-option>
                    </el-select>
                </el-form-item>
  
                <el-form-item label="管理仓库" prop="warehouseid" v-if="userForm.roleIds.includes(5)">
                    <el-select 
                        v-model="userForm.warehouseid" 
                        multiple 
                        placeholder="请选择仓库"
                        style="width: 100%;"
                    >
                        <!-- 仓库id实际存储值需要转换为字符串 -->
                        <el-option 
                            v-for="warehouse in warehouseList" 
                            :label="warehouse.name" 
                            :value="parseInt(warehouse.value)" 
                            :key="warehouse.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
  
                <el-form-item label="所属部门" prop="deptno" v-if="userForm.roleIds.includes(3) || userForm.roleIds.includes(4)">
                    <el-select 
                        v-model="userForm.deptno"
                        placeholder="请选择部门"
                        clearable
                        style="width: 100%;"
                    >
                        <el-option 
                            v-for="dept in deptList" 
                            :label="dept.dname" 
                            :value="dept.deptno" 
                            :key="dept.deptno"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="头像上传" prop="imageurl">
                    <el-upload  class="upload"  action="#"  list-type="picture-card" :show-file-list="false" :before-upload="beforeUpload"
                    :http-request="handleUpload" :on-success="handleSuccess" :on-remove="handleRemove">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                 </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                    <el-button @click="closeDialog">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: 'UserInfo',
    props: {
        isShow: Boolean,
        newEmpList: Array,
        roleList: Array,
        userInfo: Object
    },
    data() {
        return {
            imageUrl:'',
            userForm: {
                userid: '',
                empno: null,
                roleIds: [],
                warehouseid: [],  
                deptno:null,
                imageurl:''
            },
            warehouseroleid: '5',  
            deptList: [],
            warehouseList:[],
            rules: {
                empno: [
                    { required: true, message: '请选择员工', trigger: 'change' }
                ],
                roleIds: [
                    { required: true,  
                        validator: (rule, value, callback) => {
                            //将部门经理，总经理，员工设置为核心角色，检测选择的数量
                            let coreRoles = value.filter(id => [2, 3, 4].includes(id));
                            if (coreRoles.length === 0) {
                                callback(new Error('必须选择总经理、部门经理或员工中的一个角色'));
                            }   
                            else if (coreRoles.length > 1) {
                                callback(new Error('总经理、部门经理、员工三个角色只能选择一个'));
                            }
                            else {
                                callback();
                            }
                     },  trigger: 'change' }
                ],
                warehouseid: [
                    { required: true, message: '请至少选择一个仓库', trigger: 'change' }
                ],
                deptno: [
                    { required: true, message: '请选择部门', trigger: 'change' }
                ]
            },
            isEdit: false,
            showWarehouse: false
        }
    },
    watch: {
        isShow(val) {
            this.isEdit = val && !!this.userInfo.userid;
            // 弹窗显示时处理回显,等框架完全渲染才显示数据
            if (val) {
                this.$nextTick(() => {
                    this.echoUserData(this.userInfo);
                });
            } 
        },
        // 监听用户数据变化
        userInfo: {
            handler(val) {
                if (this.isShow) {
                    this.$nextTick(() => {
                        this.echoUserData(val)
                        this.imageUrl = val.imageurl
                        //回显头像
                    });
                }
            },
            //深度监听，保证数据实时更新
            deep: true
        },
    },
    methods: {
        getDeptList() {
            this.$http.post('/getDepts').then(res => {
                this.deptList = res.data
            }).catch(() => {
                this.$message.error('系统异常')
            })
        },

        echoUserData(val) {
            if (!val) {
                this.userForm = { userid: '', empno: null, roleIds: [], warehouseid: [],deptno: null,imageurl:'' };
                this.showWarehouse = false;
                return;
            }
            this.userForm = val
            this.showWarehouse = this.userForm.roleIds.includes(5)
        },
        handleRoleChange(roleIds) {
            this.showWarehouse = roleIds.includes(this.warehouseroleid);
            if (!this.showWarehouse) {
                this.userForm.warehouseid = [];
            }
        },

        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let url = this.isEdit ? '/updateUser' : '/addUser'
                    this.userForm.userid = this.userForm.empno + ''
                    let formData = { 
                        ...this.userForm
                    }
                    this.$http.post(url, formData).then(res => {
                        if (res.data === 'success') {
                            this.$emit('userSave', 'success');
                            this.closeDialog();
                        } else {
                            this.$message.error("保存失败");
                        }
                    }).catch(err => {
                        this.$message.error("提交失败");
                    });
                }
            });
        },
  
        getWareHouseList(){
          this.$http.get("/getWareHouses").then(res => {
              this.warehouseList = res.data || [];
          });
        },
  
        closeDialog() {
            this.userForm = { userid: '', empno: null, roleIds: [], warehouseid: [], deptno: null,imageurl:'' };
            this.showWarehouse = false;
            this.isEdit = false;
            this.imageUrl = null
            
            if (this.$refs.ruleForm) {
                this.$refs.ruleForm.resetFields();
            }
            this.$emit('closeDialog');
        },

        beforeUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            if (!isJPG && !isPNG) {
                 this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                 this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG || isPNG && isLt2M;
    },
        async handleUpload(config) {
          const file = config.file;
            if (this.userForm.imageurl) { 
              try {
                await this.$http.post('/deleteOrderImage', { 
                  imageUrl: this.userForm.imageurl
                });
                console.log('旧图片删除成功');
              } catch (err) {
                console.error('删除旧图片失败：', err);
                this.$message.warning('旧图片删除失败，但将继续上传新图片');
              }
            }
            const formData = new FormData();
            formData.append('file', file); 
            // 调用后端接口
            this.$http.post('/addPicture', formData, {
                headers: {
                'Content-Type': 'multipart/form-data' 
                }
            }).then(res => {
                if (res.data.code === 200) {
                    this.userForm.imageurl = res.data.data; 
                    config.onSuccess(res.data); 
                    this.$message.success('图片上传成功');
                } else {
                    config.onError(res.data); 
                    this.$message.error('图片上传失败：' + res.data.msg);
                }
            }).catch(err => {
                config.onError(err);
                this.$message.error('上传失败：网络错误');
                console.error('上传错误：', err);
            });
        },
        handleRemove(file, fileList) {
            if (fileList.length === 0) {
                this.userForm.imageurl = ''; 
                this.imageUrl = ''; 
            }
        },
        handleSuccess(res, file) {
            this.imageUrl = this.userForm.imageurl;
        },
    },
    created(){
      this.getDeptList()
      this.getWareHouseList()
    }
  }
  </script>